#include "programlist.h"
#include "IniFile.h"
#include "TStringUtil.h"


namespace tv 
{


ProgramList::ProgramList()
{

}


bool ProgramList::load(const char* filepath)
{
    clear();

    m_filepath = filepath;

    comn::IniFile iniFile;
    if (!iniFile.load(filepath))
    {
        return false;
    }

    for (size_t i = 0; i < iniFile.getSectionCount(); i ++)
    {
        comn::IniFile::IniSection& section = iniFile.getSection(i);
        Program program;
        comn::StringCast::toValue(section.name, program.num);

        section.get("name", program.name);
        section.get("memo", program.memo);
        section.get("url", program.url);
        section.get("freqNum", program.freqNum);
        section.get("freqName", program.freqName);

        push_back(program);
    }

    return true;
}

bool ProgramList::save(const char* filepath)
{
    comn::IniFile iniFile;
    for (size_t i = 0; i < size(); ++ i)
    {
        const Program& program = at(i);
        std::string num = comn::StringCast::toString(program.num);
        comn::IniFile::IniSection& section = iniFile.ensure(num.c_str());
        section.set("name", program.name);
        section.set("memo", program.memo);
        section.set("url", program.url);
        section.set("freqNum", comn::StringCast::toString(program.freqNum));
        section.set("freqName", program.freqName);
    }

    return iniFile.save(filepath);
}

size_t ProgramList::indexOf(const std::string& num)
{
    for (size_t i = 0; i < size(); ++ i)
    {
        if ((*this)[i].num == num)
        {
            return i;
        }
    }
    return -1;
}

size_t ProgramList::indexWithName(const std::string& name)
{
    for (size_t i = 0; i < size(); ++ i)
    {
        if ((*this)[i].name == name)
        {
            return i;
        }
    }
    return -1;
}

bool ProgramList::contains(const std::string& num)
{
    return indexOf(num) != -1;
}

std::string ProgramList::getFilePath()
{
    return m_filepath;
}

bool ProgramList::remove(size_t idx, Program& program)
{
    if (idx >= size())
    {
        return false;
    }

    iterator it = begin();
    std::advance(it, idx);

    program = *it;

    erase(it);

    return true;
}

bool ProgramList::remove(size_t idx)
{
    if (idx >= size())
    {
        return false;
    }

    iterator it = begin();
    std::advance(it, idx);
    erase(it);

    return true;
}

}
